.DEFAULT_GOAL := help
# 以目录名作为镜像，应用文件名
CURDIRNAME?=$(shell basename ${CURDIR})
# 可用参数定义 CURDATE 的值
CURDATE?=$(shell date '+%Y%m%d')
REGISTRY?=hub.haifengat.com/jrcxb
#===================================== git ================================#
gitpush: # git 代码提交并推送
	@if [ ! $M ]; then \
		echo "add param: M=<your comment for this commit>"; \
		exit 1; \
	fi
	git commit -a -m "${M}"
	git push origin
tag: # 添加标签（当前日期）
	# 删除当前日期的 tag
	- git tag -d ${CURDATE}
	- git push origin :refs/tags/${CURDATE}
	git tag -a ${CURDATE} -m "$(shell git log -1 --pretty=%B)" # 最后提交注释作为tag注释
	git push origin --tags
#------------------------------------------------------------------------#
#================================= 镜像处理 =============================#
build: # 编译 打包镜像
	go build -o ${CURDIRNAME}
	@# 替换容器中的 appName 以解决 entrypoint 启动程序不能用变量的问题
	sed -i 's#ENTRYPOINT.*#ENTRYPOINT ["./${CURDIRNAME}"]#g' Dockerfile
	docker build . -t ${REGISTRY}/${CURDIRNAME}:${CURDATE} --build-arg appName=${CURDIRNAME}
docker: build # 镜像推送
	docker push ${REGISTRY}/${CURDIRNAME}:${CURDATE}
publish: docker # 镜像发送 latest
	docker tag ${REGISTRY}/${CURDIRNAME}:${CURDATE} ${REGISTRY}/${CURDIRNAME}:latest
	docker push ${REGISTRY}/${CURDIRNAME}:latest
#--------------------------------------------------------------------------#
#=================================== 部署 =====================================#
# 应用服务器 pre/prod 免密登录
rm: # 清除原有容器和同版本镜像（报错则忽略），记录部署日志
	- ssh ${MAKECMDGOALS} "docker rm -f ${CURDIRNAME}; docker rmi -f ${REGISTRY}/${CURDIRNAME}:${CURDATE};"
	echo "${MAKECMDGOALS}	$(shell date '+%Y/%m/%d %H:%M:%S')	${REGISTRY}/${CURDIRNAME}:${CURDATE}" >> deploy_log
pre: rm # --restart=always 参数会导致重复报警，且 portainer 不能及时显示停止状态。
	ssh ${MAKECMDGOALS} "docker run -it -d --name ${CURDIRNAME} \
	-e TZ=Asia/Shanghai \
	--net=jcbnet \
	-e wxchatURL='http://192.168.52.201:31099/test/txt' \
	-e portainerURL='192.168.52.9:9000' \
	# -e stopDocker='52.231|ctp_risk|02:50,52.231|ctp_risk|16:00' \
	# -e restartDocker='52.201|ctp_risk|08:45,52.201|ctp_risk|15:45' \
	${REGISTRY}/${CURDIRNAME}:${CURDATE}"
prod: rm
	ssh ${MAKECMDGOALS} "docker run -it -d --name ${CURDIRNAME} \
	-e TZ=Asia/Shanghai \
	--net=jcbnet \
	-e wxchatURL='http://192.168.52.231:31099/${CURDIRNAME}/txt' \
	-e portainerURL='192.168.52.9:9000' \
	-e stopDocker='52.231|ctp_risk|02:50,52.231|ctp_risk|16:00' \
	-e restartDocker='52.231|ctp_risk|08:45,52.231|ctp_risk|20:45,52.231|ebf-cta-position|15:00' \
	${REGISTRY}/${CURDIRNAME}:${CURDATE}"
#--------------------------------------------------------------------------#
.PHONY: gitpush tag 
.PHONY: build docker publish
.PHONY: pre prod
.PHONY: help
help:
	@echo 'git提交并推送:      make gitpush M="提交说明"'
	@echo '创建tag(当前日期):  make tag'
	@echo '镜像生成并推送:     make docker'
	@echo '镜像发送latest:     make publish'
	@echo '直接部署预生产:     make pre'
	@echo '直接部署生产：      make prod'
	@echo 'make -n 检查语法'
	@echo 'make xxxx CURDATE=yyyymmdd 指定日期(版本)'
